package pathfinder

import (
	"sync"

	"gitee.com/night-tc/gobige/logger"
)

/*
把NavMesh与Finder分离了
然后把地图文件的管理 也接手了。
C++中不需要管理这部分内存；
*/
var (
	one        sync.Once
	navmeshMgr *NavMeshMgr
)

func GetMeshMgr() *NavMeshMgr {
	return navmeshMgr
}

func init() {
	one.Do(func() {
		navmeshMgr = new(NavMeshMgr)
		navmeshMgr.meshList = make(map[string]*Cgo_ObsNavMesh)
	})
}

type NavMeshMgr struct {
	// 地图信息
	meshList map[string]*Cgo_ObsNavMesh
	lock     sync.RWMutex
}

/*
那种有墙体的地图，需要通过这个生成出来后，然后添加墙体，等别人使用
*/
func (this *NavMeshMgr) GetNavMesh(filename, key string) (result *Cgo_ObsNavMesh) {
	navMesh, ok := this.getMesh(key)
	if !ok {
		navMesh = this.tryNewMesh(filename, key)
	}
	return navMesh
}

/*
静态地图
获取寻路对象
*/
func (this *NavMeshMgr) GetFinder(filename, key string) (result *FinderObs) {
	ok := false
	var navMesh *Cgo_ObsNavMesh
	var finder *Cgo_ObsPathFinder
	if key != "" {
		navMesh, ok = this.getMesh(key)
		if !ok {
			navMesh = this.tryNewMesh(filename, key)
		}
	} else {
		navMesh = newObsNavMesh(filename, key)
	}
	finder = newObsPathFinder(navMesh)
	if navMesh == nil || finder == nil {
		logger.Warnf("GetFinder(%s,%s) navmesh:%p finder:%p", filename, key, navMesh, finder)
		return nil
	}
	return &FinderObs{
		Iskey:   key != "",
		NavMesh: navMesh,
		Finder:  finder,
	}
}

func (this *NavMeshMgr) getMesh(key string) (*Cgo_ObsNavMesh, bool) {
	this.lock.RLock()
	defer this.lock.RUnlock()
	result, ok := this.meshList[key]
	return result, ok
}

func (this *NavMeshMgr) tryNewMesh(filename, key string) *Cgo_ObsNavMesh {
	this.lock.Lock()
	defer this.lock.Unlock()
	result, ok := this.meshList[key]
	if ok {
		return result
	}
	result = newObsNavMesh(filename, key)
	this.meshList[key] = result
	return result
}
